package com.gtug.hack.herbert_bangdao.Activities;

import java.util.Iterator;
import java.util.List;

import com.gtug.hack.herbert_bangdao.R;
import com.gtug.hack.herbert_bangdao.Services.MonitorService;
import com.gtug.hack.herbert_bangdao.Views.CustomWindow;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class RadioSwitchActivity extends CustomWindow {
    /** Called when the activity is first created. */
	
	private static final String TAG  = "ActivityTag";
	private TelephonyManager tm;
	




	
	// define an onclick listener for a button
	/*
	private OnClickListener mAlertButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// lets send text alert the notification bar
			String ns = Context.NOTIFICATION_SERVICE;
			NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
			int icon = R.drawable.ic_launcher;
			CharSequence tickerText = "Poor 3G signal alert";
			long when = System.currentTimeMillis();
			Notification notification = new Notification(icon, tickerText, when);

			Context context = getApplicationContext();
			CharSequence contentTitle = "Poor 3G signal observed";
			CharSequence contentText = "Click to change Radio settings";
			Intent notificationIntent = new Intent(Intent.ACTION_MAIN);
			notificationIntent.setClassName("com.android.phone", "com.android.phone.Settings");
			PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
			
			notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
			
			final int HELLO_ID = 1;

			mNotificationManager.notify(HELLO_ID, notification);
	    }
	};
	*/
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setUpViews();
    }
    
	final PhoneStateListener phoneStateListener = new PhoneStateListener() {
		@Override
		public
		void onSignalStrengthsChanged (SignalStrength signalStrength) {
			Log.i(TAG+"GSMSigASU",(signalStrength.getGsmSignalStrength()*2 -113) + "");
			signalStrength.getGsmBitErrorRate();
			signalStrength.getEvdoSnr();
			signalStrength.getEvdoEcio();
			signalStrength.getEvdoDbm();
			signalStrength.getCdmaEcio();
			
			Log.i(TAG+"cdmaDbm",signalStrength.getCdmaDbm() + "");
			
			TextView signalStrengthOut = new TextView(RadioSwitchActivity.this);
			signalStrengthOut = (TextView) findViewById(R.id.textView6);
			signalStrengthOut.setText((signalStrength.getGsmSignalStrength()*2 - 113) + " dB");
						
			Log.i(TAG+"signalStrengthOut", (int)((double)signalStrength.getGsmSignalStrength() / 31 * 100) + "");
			
			// Set progressBar
			ProgressBar signalBar = new ProgressBar(RadioSwitchActivity.this);
			signalBar = (ProgressBar) findViewById(R.id.progressBar1);
			
			if(signalStrength.getGsmSignalStrength()==99)
				signalBar.setProgress(0);
			else
				signalBar.setProgress((int)((double)signalStrength.getGsmSignalStrength() / 31 * 100));
			Log.i(TAG+"signalBar",signalStrength.getGsmSignalStrength() + "");
			
		}
		public
		void onDataConnectionStateChanged(int state, int networkType) {
			String name=null;
			switch(networkType) {
			case TelephonyManager.NETWORK_TYPE_1xRTT:	name="1xRTT";
				break;
			case TelephonyManager.NETWORK_TYPE_CDMA:	name="CDMA";
				break;
			case TelephonyManager.NETWORK_TYPE_EDGE:	name="EDGE";
				break;
			case TelephonyManager.NETWORK_TYPE_GPRS:	name="GPRS";
				break;
			case TelephonyManager.NETWORK_TYPE_HSDPA:	name="HSDPA";
				break;
			case TelephonyManager.NETWORK_TYPE_HSPA:	name="HSPA";
				break;
			case TelephonyManager.NETWORK_TYPE_HSUPA:	name="HSUPA";
				break;
			case TelephonyManager.NETWORK_TYPE_UMTS:	name="UMTS";
				break;
			case TelephonyManager.NETWORK_TYPE_EVDO_0:	name="EVDO0";
				break;
			case TelephonyManager.NETWORK_TYPE_EVDO_A:	name="EVDOA";
				break;
			case TelephonyManager.NETWORK_TYPE_IDEN:	name="IDEN";
				break;
			case TelephonyManager.NETWORK_TYPE_UNKNOWN:	
				name="UNKNOWN";
				Log.i(TAG+" NetworkType",networkType + " is UNKNOWN");
				break;
			}
			
			TextView networkTypeName = new TextView(RadioSwitchActivity.this);
			networkTypeName = (TextView) findViewById(R.id.textView4);
			networkTypeName.setText(name);
			
		}
		
		
	};

    /* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
	}



	// checks for existing running service process
    private boolean isServiceRunning(String serviceName){
        boolean serviceRunning = false;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> l = am.getRunningServices(50);
        Iterator<ActivityManager.RunningServiceInfo> i = l.iterator();
        while (i.hasNext()) {
            ActivityManager.RunningServiceInfo runningServiceInfo = (ActivityManager.RunningServiceInfo) i
                    .next();

            if(runningServiceInfo.service.getClassName().equals(serviceName)){
                serviceRunning = true;
            }
        }
        return serviceRunning;
    }
    
    
    
   
    
	private void setUpViews() {
		
		
		tm = (TelephonyManager)RadioSwitchActivity.this.getSystemService(TELEPHONY_SERVICE);
		
		// Set Operator Name to TextView on main activity
		TextView opName = new TextView(RadioSwitchActivity.this);
		opName = (TextView) findViewById(R.id.textView2);
		opName.setText(" " + tm.getNetworkOperatorName());
		
		tm.listen(phoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
		//tm.listen(phoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
				
		// captures the button from the defined layout
        //Button alertButton = (Button)findViewById(R.id.alertbutton1);
        // register a callback to be invoked this view is clicked
        //alertButton.setOnClickListener(mAlertButtonListener);
        
        // captures the button from the defined layout
        ToggleButton  monitorButton = ( ToggleButton )findViewById(R.id.toggleButton1);
        
        // checks for MonitorService process and if running the togglebutton will be set to On, otherwise Off
        monitorButton.setChecked(isServiceRunning("com.gtug.hack.herbert_bangdao.Services.MonitorService"));
        
        // register a callback to be invoked this view is clicked
        monitorButton.setOnCheckedChangeListener(new OnCheckedChangeListener(){
 
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
			
					boolean isChecked) {
					Log.e(TAG, "Service trigger check~~~");  
				
					if(isChecked){
						toast("Starting 3G Radio Monitor");
						startService(new Intent(RadioSwitchActivity.this,MonitorService.class));
					}else{
						toast("Shutdown 3G Radio Monitor");
						boolean serviceStatus = stopService(new Intent(RadioSwitchActivity.this,MonitorService.class));
						Log.i(TAG, "Service stop status: " + serviceStatus);
					}
				}
 
        });
	}

	 private void toast(String msg){
    	Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	 }
}